'use strict'

const fs = require('fs')
const path = require('path')
const mongoose = require('mongoose')
const {dbUrl} = require('./config')

mongoose.Promise = require('bluebird')
mongoose.connect(dbUrl)

const models_path = path.join(__dirname, '/app/models')

const walk = function(modelPath) {
    fs
        .readdirSync(modelPath)
        .forEach(function(file) {
            var filePath = path.join(modelPath, '/' + file)
            var stat = fs.statSync(filePath)

            if (stat.isFile()) {
                if (/(.*)\.(js|coffee)/.test(file)) {
                    require(filePath)
                }
            }
            else if (stat.isDirectory()) {
                walk(filePath)
            }
        })
}

walk(models_path)

const koa = require('koa')
const logger = require('koa-logger')
const session = require('koa-session')
const bodyParser = require('koa-bodyparser')
const app = koa()
const cors = require('koa-cors');

app.keys = ['cms']
app.use(cors());
app.use(logger())
app.use(session(app))
app.use(bodyParser())

var router = require('./config/routes')()

app
    .use(router.routes())
    .use(router.allowedMethods())

app.listen(8090)
console.log('Listening: 8090')
